package com.faxsun.web.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class StaticResourceUrlProcessor {

	private static final Logger log = LoggerFactory.getLogger(StaticResourceUrlProcessor.class);

	private static final String regex = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
	private static final String imageUploadCDNDomain = "//image.faxsun.com";
	private static final String staticCDNDomain = "//static.faxsun.com";
	private static final String mainDomain = "faxsun.com";
	private static final String waterMark = "!watermark";

	private static final String cdnConfig = "/config.upyun.properties";
	private static final Properties properties = new Properties();

	private static boolean isCdnEnable = false;

	static {
		InputStream cdnConfigInputStream = StaticResourceUrlProcessor.class.getResourceAsStream(cdnConfig);
		if (cdnConfigInputStream != null) {
			try {
				properties.load(cdnConfigInputStream);
				isCdnEnable = Boolean.valueOf(properties.getProperty("cdn.enable", "false"));

			} catch (IOException e) {
				e.printStackTrace();
				log.error("", e);
			} finally {
				try {
					cdnConfigInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 替换字符串中，img标签的src
	 * 
	 * @param content
	 *            包含img的字符串
	 * @return content中img的url替换为需要cdn的url
	 */
	public static String replaceWithCDNUrl(String content) {
		if (isCdnEnable) {
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(content);
			while (matcher.find()) {
				String imgTag = matcher.group();
				int start = imgTag.indexOf("src=\"");
				start = start + 5;
				int end = imgTag.indexOf("\"", start);
				String url = imgTag.substring(start, end);
				String cdnUrl = replaceUrlWithCDNUrl(url);
				content = StringUtils.replace(content, url, cdnUrl);
			}
		}
		return content;
	}

	/**
	 * 将URL更换为cdn路径 url example:<br/>
	 * <code>
	 * 1. /faxsun-info/upload/1.img -> //image.faxsun.com/upload/1.img!watermark <br/>
	 * 2. /shop/*.img -> //static.faxsun.com/*.img <br/>
	 * 3. http://www.faxsun.com/faxsun/img/1.img ->
	 * http://static.faxsun.com/faxsun/img/1.img <br/>
	 * 4. http://www.faxsun.com/faxsun-info/upload/1.img ->
	 * http://image.faxsun.com/upload/1.img!watermark <br/>
	 * 5. http://www.3ddayin.net/uploads/allimg/150507/1-15050G50H44V.jpg ->
	 * http://www.3ddayin.net/uploads/allimg/150507/1-15050G50H44V.jpg
	 * </code>
	 * 
	 * @param url
	 * @return 替换为cdn后的url
	 */
	public static String replaceUrlWithCDNUrl(String url) {
		if (isNeedCDNReplace(url)) {
			StringBuffer cdnUrl = new StringBuffer();
			if (url.contains("/faxsun-info/upload")) {
				cdnUrl.append(imageUploadCDNDomain);

				// 资讯的图片url均以uplaod开始
				int uploadIndex = url.indexOf("upload");
				// /upload的index
				if (uploadIndex > 0) {
					uploadIndex--;
				}

				cdnUrl.append(url.substring(uploadIndex));
				if (url.contains("/upload/")) {
					cdnUrl.append(waterMark);
				}

			} else if (url.contains("/faxsun/") || url.contains("/shop/")) {
				// 电商url，仅需cdn
				cdnUrl.append(staticCDNDomain);
				int index = url.indexOf("/shop/");
				if (index == -1) {
					index = url.indexOf("/faxsun/");
				}
				cdnUrl.append(url.substring(index));
			}
			return cdnUrl.toString();
		} else {
			return url;
		}
	}

	/**
	 * 是否需要添加水印
	 * 
	 * @param url
	 * @param isWaterMark
	 * @return
	 */
	public static String replaceUrlWithCDNUrl(String url, boolean isWaterMark) {
		String cdnUrl = replaceUrlWithCDNUrl(url);
		if (!isWaterMark) {
			int end = cdnUrl.indexOf(waterMark);
			if (end >= 0)
				cdnUrl = cdnUrl.substring(0, end);
		}
		return cdnUrl;
	}

	private static boolean isNeedCDNReplace(String url) {
		boolean isNeedCDN = isCdnEnable && !url.startsWith(imageUploadCDNDomain) && !url.startsWith(staticCDNDomain);
		int protoclMark = url.indexOf("//");
		String domain = null;
		if (protoclMark >= 0) {
			protoclMark += 2;
			domain = url.substring(protoclMark, url.indexOf("/", protoclMark));
			isNeedCDN = isNeedCDN && domain.contains(mainDomain);
		}
		return isNeedCDN;
	}
	
	/**
	 * banner cdn url
	 * @param url
	 * @return
	 */
	public static String cdnBanner(String url){
		if(isNeedCDNReplace(url)){
			StringBuffer sb=new StringBuffer(imageUploadCDNDomain);
			sb.append(url);
			sb.append("!1899x791");
			return sb.toString();
		}
		return url;
	}
	
	/**
	 * static resource url
	 * @param url
	 * @return
	 */
	public static String cdnStaticResources(String url){
		if(isNeedCDNReplace(url)){
			StringBuffer sb=new StringBuffer(staticCDNDomain);
			sb.append(url);
			return sb.toString();
		}
		return url;
	}
}
